<script setup>
import { ref } from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import { useUserStore } from '@/stores'
import { userUpdateInfoService } from '@/api/user'
import { ElMessage } from 'element-plus'

const {
  user: { id, username, nickname, email },
  getUser
} = useUserStore()
const userInfo = ref({
  id,
  username,
  nickname,
  email
})

const formRef = ref()

const rules = {
  nickname: {
    required: true,
    message: '用户昵称不能为空',
    trigger: 'blur'
  },
  email: {
    required: true,
    message: '用户邮箱不能为空',
    trigger: 'blur',
    validator: (rule, value) => {
      const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
      return regex.test(value) || '邮箱格式不正确'
    }
  }
}

// 提交表单方法
const submitForm = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    await userUpdateInfoService(userInfo.value)
    await getUser()
    ElMessage.success('修改成功')
  }
}
</script>

<template>
  <PageContainer title="个人信息">
    <el-row>
      <el-col :span="12">
        <el-form :model="userInfo" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="登录名称">
            <el-input v-model="userInfo.username" disabled></el-input>
          </el-form-item>

          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="userInfo.nickname" placeholder="请输入用户昵称"></el-input>
          </el-form-item>

          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="userInfo.email" placeholder="请输入用户邮箱"></el-input>
          </el-form-item>

          <!-- 添加提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm">修改信息</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </PageContainer>
</template>
